

package com.io.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.io.dao.SysDeptDao;
import com.io.entity.SysDeptEntity;
import com.io.service.SysDeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("sysDeptService")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDeptEntity> implements SysDeptService {

    @Override
    public List<SysDeptEntity> queryList(Map<String, Object> params) {
        List<SysDeptEntity> sysDeptEntities = baseMapper.queryList(params);
        HashMap<Long, SysDeptEntity> treeMap = new HashMap<>();
        for (SysDeptEntity sysDeptEntity : sysDeptEntities) {
            treeMap.put(sysDeptEntity.getId(), sysDeptEntity);
        }
        List<SysDeptEntity> rootTree = new ArrayList<>();
        for (Map.Entry<Long, SysDeptEntity> entry : treeMap.entrySet()) {
            if (entry.getValue().getParentId().compareTo(0L) == 0) {
                rootTree.add(entry.getValue());
            } else {
                // 父任务信息
                SysDeptEntity tasksP = treeMap.get(entry.getValue().getParentId());
                if (StringUtils.isEmpty(tasksP)) {
                    rootTree.add(entry.getValue());
                } else {
                    tasksP.getChildren().add(entry.getValue());
                }
            }
        }
        return rootTree;
    }

    @Override
    public List<Long> queryDetpIdList(Long parentId) {
        return baseMapper.queryDetpIdList(parentId);
    }

    @Override
    public List<Long> getSubDeptIdList(Long deptId) {
        //部门及子部门ID列表
        List<Long> deptIdList = new ArrayList<>();

        //获取子部门ID
        List<Long> subIdList = queryDetpIdList(deptId);
        getDeptTreeList(subIdList, deptIdList);

        return deptIdList;
    }

    /**
     * 递归
     */
    private void getDeptTreeList(List<Long> subIdList, List<Long> deptIdList) {
        for (Long deptId : subIdList) {
            List<Long> list = queryDetpIdList(deptId);
            if (list.size() > 0) {
                getDeptTreeList(list, deptIdList);
            }
            deptIdList.add(deptId);
        }
    }
}
